const db = wx.cloud.database()
const _ = db.command
const setmealCollection = db.collection('setmeal')
const setmealDishCollection = db.collection('setmeal_dish')

/**
 * 获取套餐列表
 * @param params 查询参数
 * @returns 套餐列表
 */
export const getSetmeals = async (params : any = {}) => {
	const { keyword = '', categoryId = '', page, pageSize } = params
	let where : any = {}
	let setmealList = [];

	try {
		if (categoryId) {
			where.categoryId = categoryId
		}

		if (keyword) {
			where.name = db.RegExp({ regexp: keyword })
		}

		if (!where.name && !where.categoryId) {
			where.name = _.exists(true)
		}

		if (!page && !pageSize) {
			for (var i = 0; ; i += 20) {
				const { data: list } = await setmealCollection.where(where).orderBy('createTime', 'desc').skip(i).limit(20).get()
				if (list.length === 0) break
				setmealList.push(...list)
				if (list.length < 20) break
			}
		} else {
			const skip = (page - 1) * pageSize;
			({ data: setmealList } = await setmealCollection.where(where).orderBy('createTime', 'desc').skip(skip).limit(pageSize).get())
		}
		return setmealList
	} catch (error) {
		wx.showToast({ title: error.message || '获取套餐列表失败', icon: 'none' })
		console.error('获取套餐列表失败:', error)
		throw error
	}
}

/**
 * 获取套餐菜品列表
 * @param setmealId 套餐ID
 * @returns 套餐菜品列表
 */
export const getSetmealDishes = async (setmealId : string) => {
	let setmealDishList = []
	try {
		for (var i = 0; ; i += 20) {
			const { data: list } = await setmealDishCollection.where({ setmealId }).skip(i).limit(20).get()
			if (list.length === 0) break
			setmealDishList.push(...list)
			if (list.length < 20) break
		}
		return setmealDishList
	} catch (error) {
		wx.showToast({ title: '获取套餐菜品失败', icon: 'none' })
		console.error('获取套餐菜品失败:', error)
		throw error
	}
}

/**
 * 添加套餐
 * @param setmeal 套餐数据
 * @returns 添加结果
 */
export const addSetmeal = async (setmeal : any) => {
	const { dishes, ...data } = setmeal
	let _id : string | number = ''

	try {
		wx.showLoading({ title: '稍等...', mask: true });
		const { total } = await db.collection('dish').where({ name: data.name }).count()
		if (total) {
			throw new Error('名称与菜品名称重复')
		}
		// 添加套餐基本信息
		({ _id } = await setmealCollection.add({
			data: {
				...data,
				createTime: db.serverDate(),
				updateTime: db.serverDate(),
			}
		}))

		// 添加套餐菜品关联
		if (dishes && dishes.length > 0) {
			await Promise.all(dishes.map((dish : any) =>
				setmealDishCollection.add({
					data: {
						setmealId: _id,
						dishId: dish.dishId,
						name: dish.name,
						price: dish.price,
						copies: dish.copies
					}
				})
			))
		}

		wx.hideLoading()
		return _id
	} catch (error) {
		await wx.hideLoading()
		// 事务管理：失败时删除已添加的数据
		if (_id) {
			await setmealCollection.doc(_id).remove()
			const dishList = []
			for (var i = 0; ; i += 20) {
				const { data: list } = await setmealDishCollection.field({ _id: true }).where({ setmealId: _id }).skip(i).limit(20).get()
				if (list.length === 0) break
				dishList.push(...list)
				if (list.length < 20) break
			}
			await Promise.all(dishList.map((item : any) => setmealDishCollection.doc(item._id).remove()))
		}
		wx.showToast({ title: '添加失败，检查套餐名称是否有重复', icon: 'none' })
		console.error('添加套餐失败:', error)
		throw error
	}
}

/**
 * 更新套餐
 * @param setmeal 套餐数据
 * @returns 更新结果
 */
export const updateSetmeal = async (setmeal : any) => {
	const { _id, dishes, ...data } = setmeal

	try {
		wx.showLoading({ title: '更新中...', mask: true })
		const { total } = await db.collection('dish').where({ name: data.name }).count()
		if (total) {
			throw new Error('名称与菜品名称重复')
		}
		// 更新套餐基本信息
		await setmealCollection.doc(_id).update({
			data: {
				...data,
				updateTime: db.serverDate(),
			}
		})
		// 更新套餐菜品关联
		if (dishes) {
			// 先删除原有菜品关联
			const { data: oldDishes } = await setmealDishCollection
				.field({ _id: true })
				.where({ setmealId: _id })
				.get()
			await Promise.all(oldDishes.map((item : any) =>
				setmealDishCollection.doc(item._id).remove()
			))
			// 添加新的菜品关联
			if (dishes.length > 0) {
				await Promise.all(dishes.map((dish : any) => setmealDishCollection.add({
					data: {
						setmealId: _id,
						dishId: dish.dishId,
						name: dish.name,
						price: dish.price,
						copies: dish.copies
					}
				})
				))
			}
		}
		wx.hideLoading()
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || '更新失败', icon: 'none' })
		console.error('更新套餐失败:', error)
		throw error
	}
}

//修改套餐状态
export const updateSetmealStatus = async (setmeal : any) => {
	const { _id, status } = setmeal
	try {
		wx.showLoading({ title: '稍等...', mask: true })
		if (status === 1) {
			const dishList = []
			for (var i = 0; ; i += 20) {
				const { data: list } = await setmealDishCollection.field({ dishId: true, _id: false }).where({ setmealId: _id }).skip(i).limit(20).get()
				if (list.length === 0) break
				dishList.push(...list)
				if (list.length < 20) break
			}

			if (dishList.length > 0) {
				const dishIds = [...new Set(dishList.map(item => item.dishId))]
				const { total: disableCount } = await db.collection('dish').where({ _id: _.in(dishIds), status: 0 }).count()
				if (disableCount) {
					throw new Error('套餐中有已禁售菜品，不能启售')
				}
			}
		}
		await setmealCollection.doc(_id).update({ data: { status } })
		wx.hideLoading()
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || "操作失败", icon: 'none' })
		throw error
	}
}

/**
 * 删除套餐
 * @param id 套餐ID
 * @param image 套餐图片ID
 * @returns 删除结果
 */
export const deleteSetmeal = async (id : string, image : string) => {
	try {
		wx.showLoading({ title: '删除中...', mask: true })
		// 先删除套餐菜品关联
		const dishes = []
		for (let i = 0; ; i += 20) {
			const { data: list } = await setmealDishCollection.field({ _id: true }).where({ setmealId: id }).skip(i).limit(20).get()
			if (list.length === 0) break
			dishes.push(...list)
			if (list.length < 20) break
		}
		await Promise.all(dishes.map((item : any) => setmealDishCollection.doc(item._id).remove()))
		// 删除云存储中的图片
		await wx.cloud.deleteFile({ fileList: [image] })
		// 最后删除套餐
		const res = await setmealCollection.doc(id).remove()
		wx.hideLoading()
		return res
	} catch (error) {
		await wx.hideLoading()
		wx.showToast({ title: error.message || '删除失败', icon: 'none' })
		console.error('删除套餐失败:', error)
		throw error
	}
}